package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Override
    public void checkAndDeduct(AccountDeductVo accountDeductVo) {
        //	调用服务层方法;
        int result = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (result == 0) {
            log.error("账户余额不足");
            throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
        }
    }

    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        UserAccount userAccount = userAccountMapper
                .selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
        System.out.println("userAccount = " + userAccount);
        return userAccount.getAvailableAmount();
    }

    /**
     * 用户账户的初始化
     *
     * @param userId
     */
    @Override
    public void userRegister(Long userId) {
        //创建新的账户对象
        UserAccount userAccount = new UserAccount();
        //赋值
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(new BigDecimal("1000000.00"));
        userAccount.setAvailableAmount(new BigDecimal("1000000.00"));

        //保存
        userAccountMapper.insert(userAccount);
    }
}
